package mysql

import (
	"gorm.io/gorm"
	"video-guard/videorpc/videorpc"
)

type VideoInfo struct {
	gorm.Model
	UploadUserId  int64  `gorm:"type:int(11)"`
	VideoTitle    string `gorm:"type:varchar(30);not null"`
	VideoCategory string `gorm:"type:varchar(30);not null"`
	VideoLink     string `gorm:"type:varchar(500);not null"`
	CoverLink     string `gorm:"type:varchar(500);not null"`
	VideoIntro    string `gorm:"type:varchar(100);not null"`
	PlayNum       int    `gorm:"type:int(11)"`
	LikeNum       int    `gorm:"type:int(11)"`
	CollectNum    int    `gorm:"type:int(11)"`
	CommentNum    int    `gorm:"type:int(11)"`
	VideoStatus   int    `gorm:"type:int(11)"`
	TopicId       int    `gorm:"type:int(11)"`
}

func (i *VideoInfo) FindVideoByTitle(db *gorm.DB, title string) error {
	return db.Debug().Where("video_title=?", title).Find(i).Error
}

func (i *VideoInfo) VideoAdd(db *gorm.DB) error {
	return db.Debug().Create(i).Error
}

func (i *VideoInfo) FirstVideoById(db *gorm.DB, id int64) error {
	return db.Debug().Where("id=?", id).First(i).Error
}

func (i *VideoInfo) VideoStatusUpdate(db *gorm.DB, id int64) error {
	return db.Debug().Where("id=?", id).Updates(i).Error
}

func (i *VideoInfo) PlayNumAdd(db *gorm.DB, id int64) error {
	return db.Debug().Where("id=?", id).Updates(i).Error
}

func (i *VideoInfo) CollectNumAdd(db *gorm.DB, id int64) error {
	return db.Debug().Where("id=?", id).Updates(i).Error
}

func VideoList(db *gorm.DB, sortType int64, page int64, size int64) ([]*videorpc.VideoList, error) {

	var videos []*videorpc.VideoList
	var err2 error

	if sortType == 0 {
		err2 = db.Debug().Model(&VideoInfo{}).Select(
			"cover_link",
			"video_title",
			"upload_user_id",
			"play_num",
		).Scopes(Paginate(int(page), int(size))).Order("play_num DESC").Find(&videos).Error
	} else if sortType == 1 {
		err2 = db.Debug().Model(&VideoInfo{}).Select(
			"cover_link",
			"video_title",
			"upload_user_id",
			"play_num",
		).Scopes(Paginate(int(page), int(size))).Order("created_at DESC").Find(&videos).Error
	}

	return videos, err2
}

func VideoTopicUserList(db *gorm.DB, topicId int64, userId int64, page int64, size int64) ([]*videorpc.VideoTopicUserList, error) {

	var videoTopicUser []*videorpc.VideoTopicUserList

	err2 := db.Debug().Model(&VideoInfo{}).Select(
		"video_infos.video_title",
		"video_infos.video_intro",
		"video_infos.play_num",
		"user_infos.nick_name",
		"user_infos.avatar_link",
		"topic_infos.topic_name",
	).Joins("LEFT JOIN user_infos ON user_infos.id=video_infos.upload_user_id").
		Joins("LEFT JOIN topic_infos ON topic_infos.id=video_infos.topic_id").
		Where("video_infos.upload_user_id=? OR video_infos.topic_id=?", userId, topicId).
		Scopes(Paginate(int(page), int(size))).
		Order("video_infos.play_num DESC").
		Find(&videoTopicUser).Error

	return videoTopicUser, err2
}
